<?php
namespace app\common\controller;
use think\Loader;
use think\Controller;
use think\Db;
use app\common\model\Prt;
use app\common\model\CorePayLog;
use app\common\controller\AdminBaseController;

/**
* 后台公用基础控制器
* @author taigu
* @version 2017-9-22
*/
class PaylogBaseController extends Controller {
	//打印付款日志
	function print_log($out_trade_no,$receiveAmount){
		//预付款日志
		$paylog=db("log_paylog")->where('order_sn', $out_trade_no)->find();
		if(bccomp($paylog['balance'], $receiveAmount, 2) != 0){
			// echo '数据异常';exit;
		}
		if($paylog['state']==2){
			echo '请勿重复支付';exit;
		}
		//付款用户
		$user_info = db('info_user')->where('id',$paylog['uid'])->find();
		//收款商家
		$agent_info = db('info_agent')->where('id',$paylog['agent_id'])->find();
		//支付类型
		$order_type = $paylog['order_type'];
		//实付金额
		$price	 = $paylog['balance'];
		//分销设置
		$config=get_config("fx_config");	
		//应付金额				
		$pay_money =	$paylog['origin_price'];	
		if($order_type == 1){	//订单
			$this->do_order($user_info,$paylog,$price);
		}else if($order_type == 2 ){	//扫码支付
			$this->agent_pay_qrcode($paylog,$price,$pay_money,$agent_info,$user_info,$out_trade_no);
			//商户，会员关系表
			$this->user_relevance_agent($user_info['id'],$agent_info['id'],$price);
		}else if($order_type == 7){	//单商品
			$this->goods_qrcode_pay($price,$pay_money,$paylog,$user_info,$agent_info,$out_trade_no);
			//商户，会员关系表
			$this->user_relevance_agent($user_info['id'],$agent_info['id'],$price);
		}else if($order_type == 8){	//用户鼓励金充值
			$this->do_charge($config,$paylog,$user_info,$price);//上级分佣
		}else{
			$this->oem_pay_score($paylog);
		}
	}
	//oem鼓励金充值
	function oem_pay_score($paylog){
		$result = true;
		// 启动事务
		Db::startTrans();
		//获取oem信息
		$oem_info = db('info_oem')->where('id',$paylog['uid'])->find();
		//鼓励金变化值
		$score_charge = bcmul($paylog['balance'], 100, 2);
		
		//增加oem鼓励金
		$rest1 = db('info_oem')->where('id', $oem_info['id'])->setInc('score', $score_charge);
		if(!$rest1)$result = false;
		
		//oem鼓励金记录
		$rest2 = $this->oem_score_log($oem_info['id'],5,$paylog['balance']*100,'鼓励金购买');
		if(!$rest2)$result = false;
		
		//获取总账号信息
		$sys_tongji = Db::table('sys_tongji')->where('id', 1)->find();
		//计算当前总账号鼓励金
		$scores = $sys_tongji['scores'] + $score_charge;
		//计算当前总账号充值
		$balances = $sys_tongji['balances'] + $paylog['balance'];
		//更新总账号信息
		$rest10 = Db::table('sys_tongji')->where('id', 1)->update(['scores' => $scores,'balances'=>$balances]);
		if(!$rest10)$result = false;
		
		
		//更新订单信息 
		$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2,'pay_time'=>now_time()]);
		if(!$rest12) $result = false;
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$rest13 = $this->add_corepaylog($paylog_info);
			if(!$rest13) $result = false;
		}
		
		if($result){
			// 提交事务
		    Db::commit();    
		}else{
			// 回滚事务
		    Db::rollback();
			//print $e->getMessage();
		    //$this->error('数据异常请联系管理员订单号：'.$paylog['order_sn']);
		}
	}

	//企业付款
	private function send_pay($openId,$outTradeNo,$price,$message){
	    import("payment.wxpay.Mpay");
	    $wxPay = new \WxRedpack();
	    //$oid="otx0ewIY-HKwa5p0gql3bDfp562A";
	    //$outTradeNo = order_create_no();
	    return $wxPay->mchpay($openId,$price,order_create_no(),$message);
	    
	}

	//企业付款
	public function send_pay1(){
	    import("payment.wxpay.Mpay");
	    $wxPay = new \WxRedpack();
	   $oid="otx0ewIY-HKwa5p0gql3bDfp562A";
	    $outTradeNo = order_create_no();
	    $wxPay->mchpay($oid,1,$outTradeNo,'cs');
	    return true;
	    //echo 'success';
	}

	//付款成功
	function add_corepaylog($paylog){
		$result = db('log_paylog')->where('id', $paylog['id'])->find();
		if($result){
			$corepaylog=new CorePayLog();
			unset($paylog['id']);
			$res=$corepaylog->allowField(true)->save($paylog);
		}else{
			$res= 0;
		}
		
		return $res;
	}	
	/**
	 * 用户资金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $operator 加减符号
	 * $message	资金变化详情
	 */
	function user_money_log($u_id,$order_type,$balance,$message){
		$up['balance']=['exp',"balance+$balance"];
		$up['total_balance']=['exp',"total_balance+$balance"];
		$up['total_nums']=['exp',"total_nums+1"];
		$res=Db::table('info_user')->where('id', $u_id)->update($up);
		if(!$res){
			return false;
		}
		$data = array(
			'u_id'		 	=> $u_id,
			'order_type' 	=> $order_type,
			'balance' 	 	=> $balance,
			'message' 	 	=> $message,
		    "add_time"	 	=> now_time()
		);

		$result = db('log_user_charge')->insertGetId($data);
		return $result;
	}
	
	/**
	 * 用户鼓励金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $balance	金额变化值
	 * $operator 加减符号
	 * $message	变化详情
	 */
	
	function user_score_log($u_id,$order_type,$balance,$message){

		$data = array(
			'u_id'		 =>$u_id,
			'order_type' => $order_type,
			'balance' 	 => $balance,
			'message' 	 => $message,
		    "add_time"	 => now_time()
		);
        $result = db('log_user_score')->insertGetId($data);
		return $result;
		
	}
	

	
	/**
	 * 商家资金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $message	资金变化详情
	 * $operator 加减符号
	 */
	function agent_money_log($agent_id,$order_type,$balance,$message){
		
		$res=db('info_agent')->where("id",$agent_id)->setInc("balance",$balance);
		if(!$res){
			return false;
		}
		$data = array(
			'agent_id'		=> $agent_id,
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    'balance' 	 	=> $balance,
		    "add_time"	 	=> now_time()
		);
		return db('log_agent_charge')->insert($data);
	}

	function agent_money_log1($agent_id,$order_type,$balance,$message){
		
		$data = array(
			'agent_id'		=> $agent_id,
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    'balance' 	 	=> $balance,
		    "add_time"	 	=> now_time()
		);
		return db('log_agent_charge')->insert($data);
	}
	/**
	 * 商家鼓励金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $operator 加减符号
	 */
	function agent_score_log($agent_id,$order_type,$balance,$message,$chain_id=0,$clerk_id=0){
		$data = array(
			'agent_id'		=> $agent_id,
			'chain_id' 	 	=> $chain_id,
			'clerk_id' 		=> $clerk_id,
			'balance'		=> $balance,
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    "add_time"	 	=> now_time()
		);
		return db('log_agent_score')->insert($data);
	}

	/**
	 * OEM资金变化日志
	 * 
	 * $paylog 支付日志
	 * $order_type 订单类型
	 * $balance 变化金额
	 * $operator 加减符号
	 */
	function oem_money_log($oem_id,$order_type,$balance,$message){
		$res=db('info_oem')->where("id",$oem_id)->setInc("balance",$balance);
		if(!$res){
			return false;
		}
		$data = array(
			'oem_id'			=> $oem_id,
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    'balance' 	 	=> $balance,
		    "add_time"	 	=> now_time()
		);
		return db('log_oem_charge')->insert($data);
	}
	function oem_money_log1($oem_id,$order_type,$balance,$message){
		$data = array(
			'oem_id'			=> $oem_id,
			'order_type' 	=> $order_type,
			'message' 	 	=> $message,
		    'balance' 	 	=> $balance,
		    "add_time"	 	=> now_time()
		);
		return db('log_oem_charge')->insert($data);
	}
	/**
	 * OEM鼓励金变化日志
	 */
	function oem_score_log($oem_id,$order_type,$balance,$message){		
			$data['oem_id'] = $oem_id;
			$data['order_type'] = $order_type;
			$data['balance'] = $balance;
			$data['message'] = $message;
			$data['add_time'] = now_time();
		return db('log_oem_score')->insert($data);
	}
    function add_admin_charge($user_id,$balance,$type,$message){
		$data['user_id'] = $user_id;
		$data['type'] = $type;
		$data['balance'] = $balance;
		$data['message'] = $message;
		$data['add_time'] = now_time();
		return db('admin_charge')->insert($data);
	}
	/**
	 * OEM佣金变化日志
	 */
	function oem_commission_log($oem_id,$order_type,$balance,$message){		
			$data['oem_id'] = $oem_id;
			$data['order_type'] = $order_type;
			$data['balance'] = $balance;
			$data['message'] = $message;
			$data['add_time'] = now_time();
		return db('log_oem_commission')->insert($data);
	}
	//订单
	function do_order($user_info,$paylog,$price){
		$order=db("agent_syorder")->where('sn',$paylog['order_sn'])->find();
		if(!$order){
			echo '下单失败';
		}
		//获取商户信息
		$agent_info = db('info_agent')->where('id',$paylog['agent_id'])->find();
		//检查是否开启鼓励金营销
		if($agent_info['is_score'] == 1){
			$result = true;
			Db::startTrans();
			if($order['need_score'] && $order['need_score']>0){
				//会员鼓励金记录
				$res1 = $this->user_score_log($order['user_id'],1,-$order['need_score'],'订单抵扣鼓励金');
				if(!$res1)$result = false;
				//更新会员鼓励金
				$res2 = db('info_user')->where("id",$order['user_id'])->setDec("score",$order['need_score']);
				if(!$res2)$result = false;
				//商家鼓励金记录
				$this->agent_score_log($order['agent_id'],1,$order['need_score'],'用户下单抵扣鼓励金',$order['chain_id']);
				//更新商家鼓励金
				$res21 = db('info_agent')->where("id",$order['agent_id'])->setInc("score",$order['need_score']);
				if(!$res21)$result = false;
				
				
				//更新商家，用户鼓励金变化情况(便于统计)
				db("log_paylog")
						->where('order_sn', $paylog['order_sn'])
						->update(['score'=>-$order['need_score'],'member_score' =>-$order['need_score'],'agent_score'=>$order['need_score'],'payment_type'=>1]);
				
			}else{
				if($order['give_score'] >0){
					//会员鼓励金记录
					$this->user_score_log($order['user_id'],1,$order['give_score'],'下单奖励鼓励金');
					//更新会员鼓励金
					$res3 = db('info_user')->where("id",$order['user_id'])->setInc("score",$order['give_score']);
					if(!$res3)$result = false;
					//商家鼓励金记录
					$this->agent_score_log($order['agent_id'],1,-$order['give_score'],'用户下单赠送鼓励金',$order['chain_id']);
					//更新商家鼓励金
					$res31 = db('info_agent')->where("id",$order['agent_id'])->setDec("score",$order['give_score']);
					if(!$res31)$result = false;
					
					//更新商家，用户鼓励金变化情况(便于统计)
					db("log_paylog")
							->where('order_sn', $paylog['order_sn'])
							->update(['score'=>$order['give_score'],'member_score' =>$order['give_score'],'agent_score'=>-$order['give_score'],'payment_type'=>1]);
				}
			}
		}
		$up['pay_time']=now_time();
		$up['status']=4;
		$res4=db("agent_syorder")->where("sn",$paylog['order_sn'])->update($up);
		if(!$res4)$result = false;
		
		//费率分佣
		$res5 = $this->feel_commission($paylog);
		if(!$res5)$result = false;
		
		//更新订单信息 
		$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2,'pay_time'=>now_time()]);
		if(!$rest12) $result = false;
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		$rest13 = $this->add_corepaylog($paylog_info);
		if(!$rest13) $result = false;
		
		if($result){
			Db::commit();
		}else{
			Db::rollback();
		}
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			//$this->add_corepaylog($paylog_info);
			//发送用户下单通知
			if($user_info&&$user_info['openid']){
				$remark="下单成功通知";
				if($paylog_info["member_score"]>0){
					$remark.=",鼓励金账号增加".$cut_paylog["member_score"];
				}elseif($paylog_info["member_score"]<0){
					$remark.=",使用鼓励金抵扣".$cut_paylog['member_score'];
				}
				$goods_name="消费";
				$goods=db("agent_goods")->field("goods_name")->find($paylog_info['goods_id']);
				if($goods){
					$goods_name=$goods['goods_name'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'用户付款通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$paylog_info['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>$goods,
					"color"=>"#173177"
				),
				"keyword3"=> array(
					"value"=>'到店消费',
	                "color"=>"#173177"                
				),
	            "keyword4"=> array(
	                "value"=>$paylog_info['pay_time'],
	                "color"=>"#173177"
	            ),
	             "keyword5"=> array(
	                "value"=>$paylog_info['order_sn'],
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    		sendMessage($user_info['openid'],config("tempids.order"),$data,"index/member/orders.html");	
			}
		}
		//app收款提醒
		push_msg($paylog_info['agent_id'],$paylog_info['balance']);
	}
	
	//鼓励金充值
	function do_charge($config,$paylog,$user_info,$price){
			$user_ratio = db('user_ratio')->where('id',1)->value($user_info['member_level']);   //用户等级
			$cz_score=$price*$user_ratio;    //鼓励金充值比例
			$sql_user=" update info_user set score=score+".$cz_score.", total_nums=total_nums+1,total_balance=total_balance+".$price;  //用户获得鼓励金
			$sql_user.=" where id=".$user_info['id'];
			$result = true;
			Db::startTrans();

			//生成会员购买鼓励金记录
			$res5=$this->user_score_log($user_info['id'],7,$cz_score,'鼓励金购买'.$price.'￥');    //用户购买鼓励金记录
			if(!$res5){ $result =false; } 
			
			//修改会员鼓励金
			$res1=DB::execute($sql_user);
			if(!$res1){ $result =false; }
			$up['member_score']=$price*$user_ratio;    //积分变化值
			$cut_price = $price*$config['tj_user']/100;  //推荐人分佣
			$st=1;//1分推荐会员2 分员工
			$sc_id=0;//业务员
			$sc_bili=0;//
			//如果是扫员工推荐码推荐会员的奖励给员工
			if($paylog['tj_clerk_id']){
				$st=2;
				//用户上级分佣
				$mobile=$user_info['mobile'];
				$res2=$this->user_money_log($paylog['tj_clerk_id'],2,$cut_price,'会员扫员工码'.$mobile.'充值'.$price.'￥分佣');  //分给员工
				if(!$res2) $result =false;
				//上级用户
				$up['tj_clerk_id']=$user_info['level'];
				$up['clerk_commission']=$cut_price;
			}else{
				//用户上级分佣
				$mobile=$user_info['mobile'];
				$res2=$this->user_money_log($user_info['level'],2,$cut_price,'下级会员'.$mobile.'充值'.$price.'￥分佣');
				if(!$res2) $result =false;
				//上级用户
				$up['level1']=$user_info['level'];
				$up['level1_commisssion']=$cut_price;
			}
			
			// $oem_bili=$config['tj_oem'];   //之前的省市代理分佣比例设置
			$province_bili="";
			if($user_info['agency_id']){
			$province_bili=get_oem($user_info['agency_id']);   //省代分佣比例
			}
			$agency_bili=get_oem($user_info['agency_id1']);  //市分佣比例
			$city_bili=get_oem($user_info['agency_id2']);  //区分佣比例
			$agent_yj=$price*$config['tj_agent']/100;     
            $sc_bili=0;
			$remark="推荐会员购券奖励到账通知";
			//$up['agent_score']=$agent_yj;

			//增加推荐商家鼓励金分佣
			if($user_info['tj_agent']){
				$tx_agent=db('info_agent')->where("id",$user_info['tj_agent'])->field("id,user_id,sc_id,type,ad_score")->find();
				//商家打折的时候分佣
				if($tx_agent['ad_score']>0){
					$tx_type=$tx_agent['type'];
					$remark="您好,会员购卷分佣奖励已经发放到倍券账号";
					//1分佣到零钱2到余额
					if($tx_type==2){
						$res4=$this->agent_money_log($user_info['tj_agent'],7,$agent_yj,'会员'.$user_info['id'].'充值'.$price.'￥分佣');
						}else{
							$remark="您好,会员购券分佣奖励已经发放到您的微信零钱";
							$res4=$this->agent_money_log1($user_info['tj_agent'],8,$agent_yj,'会员'.$user_info['id'].'充值'.$price.'￥分佣已发放到微信零钱');
						}
					$up['tj_agent_id']=$user_info['tj_agent'];
					$up['tj_agent_commission']=$agent_yj;
					if(!$res4){
						$result =false;
					}
				}
				
				//市场专员分佣
				if($tx_agent['sc_id']){
					$sc_bili=get_sc($tx_agent['sc_id']);
					$up['salesman_id']=$tx_agent['sc_id'];
					$up['sc_commission']=$price*$sc_bili/100;
				}
					
			}

			//区域运营商
			if($city_bili&&$user_info['agency_id2']){
					//商家打折的时候区域运营商分佣
					if($tx_agent['ad_score']>0){
					$city_fy=$city_bili-$sc_bili;    //专员由区域出
					}else{
						//商家不打折的时候区域运营商分佣
                        $city_fy=$city_bili-$sc_bili+$config['tj_agent']/2;    //专员由区域出
					}
					$city_score = $price*$city_fy/100;
					$up['agency_id2']			 = $user_info['agency_id2'];
					$up['agency_id2_commission'] = $city_score;
					$tj_city=db('info_oem')->where("id",$user_info['agency_id2'])->field('type,tx_id')->find();
					if($tj_city['type']==1&&$tj_city['tx_id']){
						$city_user=db('info_user')->where('id',$tj_city['tx_id'])->field('openid')->find();
						if($city_user){
							$res=$this->send_pay($city_user['openid'], $paylog['order_sn'],$city_score, '倍券区域运营商分佣到账');
							if($res){
								$new_rest3 = $this->oem_money_log1($user_info['agency_id2'],6,$city_score,'会员'.$mobile.'充值'.$price.'￥分佣');	
							}else{
								$new_rest3 = $this->oem_money_log($user_info['agency_id2'],6,$city_score,'会员'.$mobile.'充值'.$price.'￥分佣');
							}
							
						}else{
							$new_rest3 = $this->oem_money_log($user_info['agency_id2'],6,$city_score,'会员'.$mobile.'充值'.$price.'￥分佣');
						}
					}else{
						$new_rest3 = $this->oem_money_log($user_info['agency_id2'],6,$city_score,'会员'.$mobile.'充值'.$price.'￥分佣');
					}
					if(!$new_rest3) $result =false;
			}

			//市代理
			if($agency_bili&&$user_info['agency_id1']){

					//商家打折的时候市代理分佣
					if($tx_agent['ad_score']>0){  
						$agency_fy = $agency_bili-$city_bili;    //区域由市代出
					}else{
						//商家不打折的时候市代理分佣
						$agency_fy = $agency_bili-$city_bili+$config['tj_agent']/4;    //区域由市代出
					}

					$pro_price = $price*$agency_fy/100;
					$up['agency_id1']			 = $user_info['agency_id1'];
					$up['agency_id1_commission'] = $pro_price;
					$tj_province=db('info_oem')->where("id",$user_info['agency_id1'])->field('type,tx_id')->find();
					if($tj_province['type']==1&&$tj_province['tx_id']){
						$pro_user=db('info_user')->where('id',$tj_province['tx_id'])->field('openid')->find();
						if($pro_user){
							$res=$this->send_pay($pro_user['openid'], $paylog['order_sn'],$pro_price, '倍券市代理分佣到账');
							if($res){
								$new_rest3 = $this->oem_money_log1($user_info['agency_id1'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');	
							}else{
								$new_rest3 = $this->oem_money_log($user_info['agency_id1'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');
							}
							
						}else{
							$new_rest3 = $this->oem_money_log($user_info['agency_id1'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');
						}
					}else{
						$new_rest3 = $this->oem_money_log($user_info['agency_id1'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');
					}
					if(!$new_rest3) $result =false;
			}

			//省代理
			if($province_bili&&$user_info['agency_id']){

				//商家打折的时候省代理分佣
				if($tx_agent['ad_score']>0){  
					$province_fy = $province_bili-$agency_bili;   //专员由区域出
				}else{
					//商家不打折的时候省代理分佣
					$province_fy = $province_bili-$agency_bili+$config['tj_agent']/4;    //专员由区域出
				}

				$pro_price = $price*$province_fy/100;
				$up['agency_id']			 = $user_info['agency_id'];
				$up['agency_id_commission'] = $pro_price;
				$tj_province=db('info_oem')->where("id",$user_info['agency_id'])->field('type,tx_id')->find();
				if($tj_province['type']==1&&$tj_province['tx_id']){
					$pro_user=db('info_user')->where('id',$tj_province['tx_id'])->field('openid')->find();
					if($pro_user){
						$res=$this->send_pay($pro_user['openid'], $paylog['order_sn'],$pro_price, '倍券省代理分佣到账');
						if($res){
							$new_rest3 = $this->oem_money_log1($user_info['agency_id'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');	
						}else{
							$new_rest3 = $this->oem_money_log($user_info['agency_id'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');
						}
						
					}else{
						$new_rest3 = $this->oem_money_log($user_info['agency_id'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');
					}
				}else{
					$new_rest3 = $this->oem_money_log($user_info['agency_id'],6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');
				}
				if(!$new_rest3) $result =false;
		}


			//倍券总运营商
			if($config['tj_oem']){
				//服务商佣金
				if($province_bili){
					//存在省代理平台分佣，存在省代时商家打不打折都和平台没关系  
					$pro_price = $price*(100-$config['oem_pt']-$province_bili-$config['tj_agent']-$config['tj_user'])/100;
				}else{
					if($tx_agent['ad_score']>0){
						//商家打折的时候不存在省代理平台分佣  
						$pro_price = $price*(100-$config['oem_pt']-$agency_bili-$config['tj_agent']-$config['tj_user'])/100;
					}else{
						//商家不打折的时候不存在省代理平台分佣
						$pro_price =$price*(100-$config['oem_pt']-$agency_bili-$config['tj_agent']-$config['tj_user']+$config['tj_agent']/4)/100;
					}
				}

				$up['oem_id']	      =1;
				$up['oem_commission'] = $pro_price;
				//新增服务商佣金
				$new_rest3 = $this->oem_money_log(1,6,$pro_price,'会员'.$mobile.'充值'.$price.'￥分佣');
				if(!$new_rest3) $result =false;
			}

			$longxin_price= $price*$config['oem_pt']/100;
			//龙信分
			$this->add_admin_charge($user_info['id'],$longxin_price,2,"鼓励金充值分佣");
			
			$up['state']=2;
			$up['pay_time']=now_time();
			//更新订单信息 
			$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update($up);
			if(!$rest12) $result =false;
			
			//获取订单信息
			$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
			$rest13 = $this->add_corepaylog($paylog_info);	
			if(!$rest13) $result =false;
			
			if($result){
				Db::commit();
				if(isset($tx_agent)){
					$tx_user=db("info_user")->where("id",$tx_agent['user_id'])->field("nickname,openid")->find();
					$res=$this->send_pay($tx_user['openid'], $paylog['order_sn'], $agent_yj, $remark);
					if(!$res){
						$up_agent['balance']=['exp','balance+'.$agent_yj];
						db('info_agent')->where("id",$tx_agent['id'])->update($up_agent);
					}
					$this->appmess($tx_user['openid'],$tx_user['nickname'],$agent_yj,$remark);
				}
				$st_id=$user_info['level'];
				if($st==2){
					$st_id=$paylog['tj_clerk_id'];
				}else{
					
				}
				$tj_clerk=db("info_user")->where("id",$st_id)->field("openid")->find();
				$res=$this->send_pay($tj_clerk['openid'], $paylog['order_sn'], $cut_price, '倍券推荐会员充值分佣到账');
				if(!$res){
					$up_user['balance']=['exp','balance+'.$cut_price];
					db('info_user')->where("id",$st_id)->update($up_user);
				}
				if($sc_id&&$sc_bili){
					$tj_clerk=db("info_user")->where("id",$sc_id)->field("openid")->find();
					$res=$this->send_pay($tj_clerk['openid'], $paylog['order_sn'], $price*$sc_bili/100, '倍券会员充值分佣到账');
					if(!$res){
						$up_user['balance']=['exp','balance+'.$price*$sc_bili/100];
						db('info_user')->where("id",$sc_id)->update($up_user);
					}
				}
			}else{
				Db::rollback();
			}
		if($paylog_info['state'] == 2) {
			if($user_info&&$user_info['openid']){
				$data=array(
			 	"first" => array(
	                "value"=>"充值成功，请及时查看！"
	            ),
	            "keyword1"=>array(
	               	"value"=>$paylog_info['balance']."￥"
				   ),
				"keyword2"=>array(
					"value"=>$user_info['balance']."￥"
				),
				"keyword3"=> array(
					"value"=>$user_info['score']+$paylog_info['member_score']
				),
	            "keyword4"=> array("value"=>date('Y-m-d H:i:s')),
	            "remark"=> array(
	                "value"=>"会员充值须知：鼓励金是用作消费时抵部分现金使用，并已确认了附近有合作实体店铺！"
	            ),
			 );
	    		sendMessage($user_info['openid'],config("tempids.glj_cz"),$data,config("WEB_DOMAIN")."index/member/glj.html");	
			}	
		}
	}

	function appmess($openid,$user_name,$money,$remark){
		$data=array(
		 	"first" => array("value"=>"推荐会员购券到奖励"),
		 	"keyword2"=>array("value"=>$user_name),
            "keyword2"=>array("value"=>$money),
            "keyword3"=>array("value"=>now_time()),
            "remark"=> array("value"=>$remark),
		 );
	    sendMessage($openid,config("tempids.mess"),$data);	
	}
	//扫码付款
	function agent_pay_qrcode($paylog,$price,$pay_money,$agent_info,$user_info,$out_trade_no){
		$result = true;
		// 启动事务
		Db::startTrans();
			
				//判断商家是否抵扣鼓励金
				if($agent_info['ad_score']>0&&($pay_money * 100!=$paylog['np_price']*100)){
					//商家抵扣鼓励金比例
					$counteract = bcdiv($agent_info['ad_score'], 100, 4);
					//计算抵扣鼓励金 = 应付金额 -实付金额
					$score_change = bcsub($paylog['origin_price'], $paylog['balance'], 2);
					if($score_change>0){
						//更新商家，用户鼓励金变化情况(便于统计)
						db("log_paylog")
							->where('order_sn', $out_trade_no)
							->update(['score'=>$score_change,'member_score' =>-$score_change,'agent_score'=>$score_change,'payment_type'=>2]);
						
						//减用户鼓励金
						$rest7 = db('info_user')->where('id', $user_info['id'])->setDec('score', $score_change);
						if(!$rest7) $result = false;
						
						//用户鼓励金记录
						$rest8 = $this->user_score_log($paylog['uid'],5,-$score_change,"在商家".$agent_info['agent_name']."消费,抵扣鼓励金:".$score_change);
						if(!$rest8) $result = false;
						
						//加商家鼓励金
						$rest9 = db('info_agent')->where('id', $agent_info['id'])->setInc('score', $score_change);
						if(!$rest9) $result = false;
						
						//商家鼓励金记录
						$rest10 = $this->agent_score_log($agent_info['id'],3,$score_change,"收取用户".$user_info['mobile']."鼓励金抵扣:".$score_change,$paylog['chain_id'],$paylog['clerk_id']);
						if(!$rest10) $result = false;
					}
					
				}
				
				
				//更新订单信息 
				$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2,'pay_time'=>now_time()]);
				if(!$rest12) $result = false;
				
				//获取日志
				$cut_paylog = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
				//修改订单状态
				$rest13 = $this->add_corepaylog($cut_paylog);
				if(!$rest13) $result = false;
				
				if($result){
					//提交
					Db::commit();
				}else{
					//回滚
				    Db::rollback();
				    exit;
				}
				

		if($cut_paylog['state'] == 2){
			//修改订单状态
			//$this->add_corepaylog($cut_paylog);
			//发送用户付款通知
			if($user_info&&$user_info['openid']){
				$remark="付款成功";
				if($cut_paylog["member_score"]>0){
					$remark.=",鼓励金账号增加".$cut_paylog["member_score"];
				}elseif($cut_paylog["member_score"]<0){
					$remark.=",使用鼓励金抵扣".$cut_paylog['member_score'];
				}
				$data=array(
			 	"first" => array("value"=>'付款成功通知'),
	            "keyword1"=>array("value"=>$cut_paylog['balance']),
				"keyword2"=>array("value"=>$agent_info['agent_name']),
				"keyword3"=> array("value"=>$cut_paylog['order_sn']),
	            "keyword4"=> array("value"=>date('Y-m-d H:i:s')),
	            "remark"=> array("value"=>$remark),
			 );
	    	sendMessage($user_info['openid'],config("tempids.fk"),$data,config("WEB_DOMAIN")."index/member/index.html");	
			}
			//发送商户收款通知
			if($agent_info){
				$agent_user=db('info_user')->find($agent_info['user_id']);
				if(!$agent_user['openid']){
					return;
				}
				$remark="收款成功通知";
				if($cut_paylog["agent_score"]>0){
					$remark.=",用户抵扣回收鼓励金".$cut_paylog["agent_score"];
				}elseif($cut_paylog["agent_score"]<0){
					$remark.=",用户付款赠送鼓励金".$cut_paylog['agent_score'];
				}
				$chain_name=$agent_info['agent_name'];
				if($cut_paylog['chain_id']){
					$chain=db('agent_store')->field("store_name")->find($cut_paylog['chain_id']);
					$chain_name=$chain['store_name'];
				}
				$data=array(
			 	"first" => array("value"=>'用户付款通知'),
	            "keyword1"=>array("value"=>$chain_name),
	            "keyword2"=>array("value"=>$cut_paylog['balance']),
				"keyword3"=>array("value"=>$cut_paylog['origin_price']),
				"keyword4"=> array("value"=>date('Y-m-d H:i:s')),
	            "keyword5"=> array("value"=>$cut_paylog['order_sn']),
	            "remark"=> array("value"=>$remark),
			 );
	    	sendMessage($agent_user['openid'],config("tempids.sk"),$data);	
			}
		}
		$store_switch = db('agent_prt')->where('agent_id',$agent_info['id'])->value('store_switch');
		if($store_switch == 0){
			$prt=new Prt();	
			$prt->print_store($cut_paylog['id']);	
		}
		
		//app收款提醒
		push_msg($cut_paylog['agent_id'],$cut_paylog['balance']);
		
	}
	
	
	
	//商家鼓励金充值
	function agent_pay_score($paylog,$agent_info){
		$result = true;
		// 启动事务
		Db::startTrans();
		//鼓励金变化值
		$score_charge = bcmul($paylog['balance'], 10, 2);
		//增加商家鼓励金
		$rest1 = db('info_agent')->where('id', $agent_info['id'])->setInc('score', $score_charge);
		if(!$rest1)$result = false;
		
		//商家鼓励金记录
		$rest2 = $this->agent_score_log($agent_info['id'],5,$score_charge,'鼓励金购买');
		if(!$rest2)$result = false;
		
		//获取总账号信息
		$sys_tongji = Db::table('sys_tongji')->where('id', 1)->find();
		//计算当前总账号鼓励金
		$scores = $sys_tongji['scores'] + $score_charge;
		//计算当前总账号充值
		$balances = $sys_tongji['balances'] + $paylog['balance'];
		//更新总账号信息
		$rest10 = Db::table('sys_tongji')->where('id', 1)->update(['scores' => $scores,'balances'=>$balances]);
		if(!$rest10)$result = false;
		
		//更新订单信息 
		$rest12 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2,'pay_time'=>now_time()]);
		if(!$rest12) $result = false;
		
		
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			$rest13 = $this->add_corepaylog($paylog_info);
			if(!$rest13) $result = false;
		}
		
		
		if($result){
			// 提交事务
		    Db::commit();    
		}else{
			// 回滚事务
		    Db::rollback();
			//print $e->getMessage();
		}
	}
	
	
	
	//单产品二维码收银
	function goods_qrcode_pay($price,$pay_money,$paylog,$user_info,$agent_info,$out_trade_no){
		$result = true;
		// 启动事务
		Db::startTrans();
		//付款金额1才可以赠送鼓励金
		$bijiao = bccomp(floatval($pay_money), floatval(1), 2);	
		//获取商品信息
		$goods_info = db('agent_goods')->where('id',$paylog['goods_id'])->find();
		$give_score=0;
		$need_score=0;
		//开启 鼓励金营销
		if($agent_info['is_score'] == 1 && $bijiao>=0){
			//判断商品是否赠送鼓励金
				if($paylog['member_score']>0){
					
				}else if($paylog['agent_score']>0){
						$score_change = $paylog['agent_score'];
						$need_score=$paylog['agent_score'];
						//减用户鼓励金
						$rest7 = db('info_user')->where('id', $user_info['id'])->setDec('score', $score_change);
						if(!$rest7) $result =false; 
						
						//用户鼓励金记录	
						$rest8 = $this->user_score_log($user_info['id'],5,-$score_change,"在商家".$agent_info['agent_name']."消费,抵扣鼓励金:".$score_change);
						if(!$rest8) $result =false; 
						
						//加商家鼓励金
						$rest9 = db('info_agent')->where('id', $agent_info['id'])->setInc('score', $score_change);
						if(!$rest9) $result =false; 
						
						//商家鼓励金记录 	
						$rest10 = $this->agent_score_log($agent_info['id'],3,$score_change,"收取用户".$user_info['mobile']."鼓励金抵扣:".$score_change,$paylog['chain_id'],$paylog['clerk_id']);
						if(!$rest10) $result =false; 
				}
			
			$msg['name'] = $price;
			
			//计算剩余库存
			$goods_stock = $goods_info['stock'] - $paylog['goods_num'];
			//计算累计销量
			$goods_sales = $goods_info['sales'] + $paylog['goods_num'];
			//判断是否抵扣
			if(($paylog['balance'] * 100) == ($paylog['origin_price'] * 100)){
				//累计销售金额
				$total_money 	= bcadd($goods_info['total_money'], bcmul($goods_info['original_price'], $paylog['goods_num']), 2);
				//累计赠送积分
				$total_give_score = bcadd($goods_info['total_give_score'], $give_score);
				//累计抵扣积分	
				$total_need_score = $goods_info['total_need_score'];
			}else{
				//累计销售金额
				$total_money 	= bcadd($goods_info['total_money'], bcmul($goods_info['sale_price'], $paylog['goods_num']), 2);
				//累计赠送积分
				$total_give_score = $goods_info['total_give_score'];
				//累计抵扣积分	
				$total_need_score = bcadd($goods_info['total_need_score'], $need_score);
			}
			
			//减库存
			$rest11 = Db::table('agent_goods')
						->where('id', $goods_info['id'])
						->update(['stock' => $goods_stock,
									'sales'=>$goods_sales,
									'total_money'=>$total_money,
									'total_give_score'=>$total_give_score,
									'total_need_score'=> $total_need_score
									]);
			if(!$rest11) $result =false;
			
		
			
			//更新订单信息 
			$rest15 = db('log_paylog')->where('order_sn',$paylog['order_sn'])->update(['state' => 2,'pay_time'=>now_time()]);
			if(!$rest15) $result = false;
			
			//获取订单信息
			$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
			$rest16 = $this->add_corepaylog($paylog_info);
			if(!$rest16) $result = false;
			if($result){
				//提交
				Db::commit();
			}else{
				 //dump($e->getMessage());
			    //回滚
			    Db::rollback();
			    exit;
			}
		}
		//获取订单信息
		$paylog_info = db("log_paylog")->where('order_sn', $paylog['order_sn'])->find();
		if($paylog_info['state'] == 2) {
			//$this->add_corepaylog($paylog_info);
			//发送用户付款通知
			if($user_info&&$user_info['openid']){
				$remark="付款成功";
				if($paylog_info["member_score"]>0){
					$remark.=",鼓励金账号增加".$paylog_info["member_score"];
				}elseif($paylog_info["member_score"]<0){
					$remark.=",使用鼓励金抵扣".$paylog_info['member_score'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'付款成功通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$paylog_info['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword2"=>array(
					"value"=>$agent_info['agent_name'],
					"color"=>"#173177"
				),
				"keyword3"=> array(
					"value"=>$paylog_info['order_sn'],
	                "color"=>"#173177"                
				),
	            "keyword4"=> array(
	                "value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($user_info['openid'],config("tempids.fk"),$data,config("WEB_DOMAIN")."index/member/index.html");	
			}
			//发送商户收款通知
			if($agent_info){
				$agent_user=db('info_user')->find($agent_info['user_id']);
				if(!$agent_user['openid']){
					return;
				}
				$remark="收款成功通知";
				if($paylog_info["agent_score"]>0){
					$remark.=",用户抵扣回收鼓励金".$paylog_info["agent_score"];
				}elseif($paylog_info["agent_score"]<0){
					$remark.=",用户付款增送鼓励金".$paylog_info['agent_score'];
				}
				$chain_name=$agent_info['agent_name'];
				if($paylog_info['chain_id']){
					$chain=db('agent_store')->field("store_name")->find($paylog_info['chain_id']);
					$chain_name=$chain['store_name'];
				}
				$data=array(
			 	"first" => array(
	                "value"=>'用户付款通知',
	            	"color"=>"#173177"
	            ),
	            "keyword1"=>array(
	               	"value"=>$chain_name,
	               	"color"=>"#173177"
				   ),
	            "keyword2"=>array(
	               	"value"=>$paylog_info['balance'],
	               	"color"=>"#173177"
				   ),
				"keyword3"=>array(
					"value"=>$paylog_info['origin_price'],
					"color"=>"#173177"
				),
				"keyword4"=> array(
					"value"=>date('Y-m-d H:i:s'),
	                "color"=>"#173177"                
				),
	            "keyword5"=> array(
	                "value"=>$paylog_info['order_sn'],
	                "color"=>"#173177"
	            ),
	            "remark"=> array(
	                "value"=>$remark,
	                "color"=>"#173177"
	            ),
			 );
	    	sendMessage($agent_user['openid'],config("tempids.sk"),$data);	
			}
		}
		
		$paid = db('agent_prt')->where('agent_id',$agent_info['id'])->value('paid');
		if($paid == 0){
			$prt=new Prt();	
			$prt->print_order3($paylog_info['id']);	
		}
			
		//app收款提醒
		push_msg($paylog_info['agent_id'],$paylog_info['balance']);
	}
	
	//用户商家关系
	function user_relevance_agent($u_id,$agent_id,$balance){
		
		$user_relevance_agent = db('user_relevance_agent')
								->where('user_id',$u_id)
								->where('agent_id',$agent_id)
								->find();
			$relevance['add_time']=now_time();
			if($user_relevance_agent){
				$relevance['total_money'] = bcadd($user_relevance_agent['total_money'], $balance, 2);
				$relevance['total_num'] = $user_relevance_agent['total_num']+1;
				return Db::table('user_relevance_agent')
						->where('id', $user_relevance_agent['id'])
						->update($relevance);
			}else{
				$relevance['user_id'] = $u_id;
				$relevance['agent_id'] = $agent_id;
				$relevance['total_money'] = $balance;
				$relevance['total_num'] = 1;
				return Db::table('user_relevance_agent')->insert($relevance);
			}
	}
	
	//费率分佣
	function feel_commission($paylog){
		$result = true;
		
		//oem佣金费率
		$pay_feel = config('pay_feel');
		
		//计算当前费率
		$oem_feel =  bcsub($pay_feel, 0.0025, 4);
		
		$oem_id = config('cut_oem_id');
		//计算oem费率佣金
		$oem_commission = bcmul($paylog['balance'], $oem_feel, 4);
		if($oem_commission>0){
			//更新oem佣金
			$resut1 = Db::table('info_oem')->where('id', $oem_id)->setInc('commission',$oem_commission);
			if(!$resut1) $result = false;
			
			//新增oem佣金记录
			$resut2 = $this->oem_commission_log($oem_id,7,$oem_commission,'商家收款费率：'.$oem_commission);
			if(!$resut2) $result = false;
		}
		
		
		return $result;
	}
	
	
	
}
